<?php
namespace GRH\Model\Table;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;

use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Select;

use GRH\Model\PeriodeDetails;

class PeriodeDetailsTable extends AbstractTableGateway
{
    protected $table = 'grh_periode_details';
    
    /**
     * Constructeur
     * 
     * @param \Zend\Db\Adapter\Adapter $adapter
     */
    public function __construct(Adapter $adapter)
    {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new PeriodeDetails());
        $this->initialize();
    }
    
    public function getAll()
    {
        return $this->select();
    }
    
    public function get($id)
    {
        $id = (int)$id;
        $row = $this->table
                ->select(array('periode_details_id' => $id))
                ->current();
        if(!$row)
            throw new \Exception("PeriodeDetailsTable::get => Impossible de trouver '$id'");
        
        return $row;
    }
    
    /**
     * Sauvegarder un détails de période
     * 
     * @param \GRH\Model\PeriodeDetails $details
     * @return type
     * @throws \Exception
     */
    public function save(PeriodeDetails $details)
    {
        $data = array(
            'periode_id' => $details->periode_id,
            'semaine_id' => $details->semaine_id,
        );
        $id = (int)$details->periode_details_id;
        if($id == 0)
            $this->insert ($data);
        else
            if($this->get($id))
                $this->update ($data, array('periode_details_id' => $id));
            else
                throw new \Exception("PeriodeDetailsTable::save => Impossible de trouver '$id'");
            
        if($id == 0) return $this->lastInsertValue;
        else return $id;
    }
    
    /**
     * Effacer un détails de période
     * 
     * @param type $id
     */
    public function delete($id)
    {
        $this->delete(array('periode_details_id' => $id));
    }
}